package com.neusoft.dibuy.tyut.net.server;

import com.neusoft.dibuy.tyut.net.cfg.NetConfig;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Demo2App {

    /**
     * TODO : ServerSocket 将一直保持监听
     * @param args
     * @throws IOException
     */

    public static void main(String[] args) throws IOException {
//        打开端口，进行侦听
        ServerSocket serverSocket = new ServerSocket(NetConfig.MSG_PORT);
        System.out.println(1);
//        侦听到，建立连接，进行通信
        System.out.println("2.........");
        /**
         *  serverSocket.accept()
         *  1、组赛线程
         *  2、如果有客户端请求，则新建立Socket
         */
        while (NetConfig.RUNNING){
            System.out.println("3.........");
            Socket socket = serverSocket.accept();
            System.out.println(4);
            Thread t = new NetThread(socket);
            t.start();
            System.out.println("5.........");
        }
        serverSocket.close();
        System.out.println("Hello world!");
    }
}

class NetThread extends Thread{
    private Socket socket;
    private   InputStream inputStream;
    public NetThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            this.inputStream = socket.getInputStream();
            byte[] bytes = new byte[NetConfig.MSG_LENGTH];
            inputStream.read(bytes);
            String msg = new String(bytes);
            System.out.println(msg);
        }catch (Exception e)
        {
            System.out.println(e.getMessage());
        }finally {
           try {
               this.inputStream.close();
               socket.close();
           }catch (Exception e){

           }
        }
    }
}
